import paramiko
from paramiko.channel import ChannelStdinFile, ChannelFile, ChannelStderrFile


class LinuxShell:

    # 初始化ssh
    def __init__(self,
                 hostname: str,
                 port: int = 22,
                 username=None,
                 password=None
                 ):
        self.ssh = paramiko.SSHClient()
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.ssh.connect(
            hostname,
            port,
            username,
            password
        )

    def exec(self, cmd: str) -> tuple[ChannelStdinFile, str, str]:
        # 执行shell命令
        stdin, stdout, stderr = self.ssh.exec_command(cmd)

        # 关闭stdin
        stdin.close()

        # 读取stdout内容
        stdout_content = stdout.read().decode("utf_8")
        # 关闭stdout
        stdout.close()

        # 读取stderr内容
        stderr_content = stderr.read().decode("utf_8")
        # 关闭stderr
        stderr.close()

        return stdin, stdout_content, stderr_content

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.ssh.close()




